package com.jacken;

import io.jsonwebtoken.*;
import org.junit.Test;

import java.util.Date;
import java.util.UUID;

public class jwt {
    private static long tokenExpiration = 1000 * 60 * 60 * 24;
    private static String tokenSignKey = "jacken123";

    @Test
    public void test1(){
        JwtBuilder jwtBuilder = Jwts.builder();
        // 头，载荷，签名哈希
        String jwtToken = jwtBuilder
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                // 载荷部分的自定义信息
                .claim("nickname", "jacken")
                .claim("avatar", "1.jpg")
                .claim("role", "admin")
                // 主题
                .setSubject("srb-user")
                .setIssuer("jacken")
                .setAudience("yy")
                // 生成时间
                .setIssuedAt(new Date())
                // 过期时间
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                // 生效时间
                .setNotBefore(new Date(System.currentTimeMillis() + 1000 * 20))
                // jti,每次生成都生成唯一的标识符
                .setId(UUID.randomUUID().toString())
                // 签名哈希
                .signWith(SignatureAlgorithm.HS256, tokenSignKey)
                // 组成jwt字符串
                .compact();

        System.out.println(jwtToken);

    }

    // 解析JWT
    @Test
    public void testGetUserInfoByJWT(){
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuaWNrbmFtZSI6ImphY2tlbiIsImF2YXRhciI6IjEuanBnIiwicm9sZSI6ImFkbWluIiwic3ViIjoic3JiLXVzZXIiLCJpc3MiOiJqYWNrZW4iLCJhdWQiOiJ5eSIsImlhdCI6MTYzNjA4MzgwMywiZXhwIjoxNjM2MTcwMjAzLCJuYmYiOjE2MzYwODM4MjMsImp0aSI6ImM1MjA2MTczLTA1ODYtNGQwZC05ZDFiLWUzY2Y4MWE5ZDI5YSJ9.ljHPNH1rPhUpuStCa-s6EGDxFfNuM5NGovqDYGU-8rI";

        JwtParser jwtParser = Jwts.parser();

        Jws<Claims> claimsJws = jwtParser.setSigningKey(tokenSignKey).parseClaimsJws(token);

        // 载荷
        Claims claims= claimsJws.getBody();

        String nickname = (String) claims.get("nickname");

        String avatar = (String) claims.get("avatar");

        String role = (String) claims.get("role");

        String id = claims.getId();
        System.out.println("nickname:"+nickname+'\n'+"avatar:"+avatar+"\n"+"role:"+role+"\n"+"id:"+id);

    }
}
